// https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

#include <iostream>
#include <vector>
using namespace std;


struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};


class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        if (pHead == nullptr || pHead->next == nullptr || pHead->next->next == nullptr) {
            return nullptr;
        }
        ListNode* slow = pHead->next;
        ListNode* fast = pHead->next->next;
        while(slow != fast && fast != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        if (fast == nullptr) {
            return nullptr;
        }

        ListNode* c = pHead;
        while (c != slow) {
            c = c->next;
            slow = slow->next;
        }
        return c;
    }
};